<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :before-close="closeHandle"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
     <el-form-item label="商品类别" prop="typename">
        <el-popover
          ref="typeListPopover"
          placement="bottom-start"
          trigger="click">
          <el-tree
            :data="typeList"
            :props="typeListTreeProps"
            node-key="id"
            ref="typeListTree"
            @current-change="typeListTreeCurrentChangeHandle"
            :default-expand-all="true"
            :highlight-current="true"
            :expand-on-click-node="false">
          </el-tree>
        </el-popover>
        <el-input v-model="dataForm.typename" v-popover:typeListPopover :readonly="true" placeholder="点击选择类别" class="menu-list__input"></el-input>
    </el-form-item>
    <el-form-item label="商品名称" prop="name">
      <el-input v-model="dataForm.name" placeholder="美食名称"></el-input>
    </el-form-item>
    <el-form-item label="单价" prop="price">
      <el-input v-model="dataForm.price" placeholder="单价"></el-input>
    </el-form-item>
    <el-form-item label="显示" prop="isshow">
    <el-radio-group v-model="dataForm.isshow">
      <el-radio :label="0">上架</el-radio>
      <el-radio :label="1">下架</el-radio>
    </el-radio-group>
    </el-form-item>
    <el-form-item label="排序" prop="sort">
      <el-input v-model="dataForm.sort" placeholder="排序"></el-input>
    </el-form-item>
    <el-form-item label="图片" prop="imgurl">
      <el-upload
        accept="image/jpeg,image/gif,image/png,image/bmp"
        :action="url"
        :before-upload="beforeUploadHandle"
        :on-success="successHandle"
        :on-remove="handleRemove"
        :on-exceed="limit"
        :multiple="false"
        :file-list="fileList"
        :limit="1"
        list-type="picture-card">
        <i class="el-icon-plus"></i>
      </el-upload>
    </el-form-item>
    <el-form-item label="描述" prop="describe">
      <el-input v-model="dataForm.describe" placeholder="描述"></el-input>
    </el-form-item>
    <el-form-item label="备注" prop="remark">
      <el-input v-model="dataForm.remark" placeholder="备注"></el-input>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false, fileList=[]">取消</el-button>
      <el-button type="primary" :disabled="subable" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
   import { treeDataTranslate } from '@/utils'
export default {
     data () {
       return {
         subable: false,
         visible: false,
         url: '',
         num: 0,
         successNum: 0,
         fileList: [],
         filename: '',
         dataForm: {
           id: 0,
           typename: '',
           typeid: '',
           name: '',
           price: '',
           describe: '',
           tag: '',
           remark: '',
           isshow: 0,
           sort: 0,
           imgurl: ''
         },
         dataRule: {
           typename: [
             { required: true, message: '商品类别不能为空', trigger: 'blur' }
           ],
           name: [
            { required: true, message: '商品名称不能为空', trigger: 'blur' }
           ],
           sort: [
            { required: true, message: '排序不能为空', trigger: 'blur' }
           ]
         },
         typeList: [],
         typeListTreeProps: {
           label: 'typename',
           children: 'children'
         }
       }
     },
     methods:
     {
       init: function (id) {
         this.url = this.$http.adornUrl(`/good/good/upload?token=${this.$cookie.get('token')}`)
         this.dataForm.id = id || 0
         this.$http({
           url: this.$http.adornUrl('/good/good/selecttypelist'),
           method: 'get',
           params: this.$http.adornParams()
         }).then(({data}) => {
           this.typeList = treeDataTranslate(data.typeList, 'id')
         }).then(() => {
           this.visible = true
           this.$nextTick(() => {
             this.subable = false
             this.$refs['dataForm'].resetFields()
           })
         }).then(() => {
           if (!this.dataForm.id) {
             // 新增
             this.typeListTreeSetCurrentNode()
           } else {
              // 修改
             this.$http({
               url: this.$http.adornUrl(`/good/good/info/${this.dataForm.id}`),
               method: 'get',
               params: this.$http.adornParams()
             }).then(({data}) => {
               if (data && data.code === 0) {
                 this.dataForm.typename = data.good.typename
                 this.dataForm.typeid = data.good.typeid
                 this.dataForm.name = data.good.name
                 this.dataForm.price = data.good.price
                 this.dataForm.describe = data.good.describe
                 this.dataForm.tag = data.good.tag
                 this.dataForm.remark = data.good.remark
                 this.dataForm.isshow = data.good.isshow
                 this.dataForm.sort = data.good.sort
                 this.fileList = eval(data.good.imgurl)
               }
             })
           }
         })
       },
       typeListTreeCurrentChangeHandle (data, node) {
         this.dataForm.typeid = data.id
         this.dataForm.typename = data.typename
       },
      // 菜单树设置当前选中节点
       typeListTreeSetCurrentNode () {
         this.$refs.typeListTree.setCurrentKey(this.dataForm.typeid)
         this.dataForm.typename = (this.$refs.typeListTree.getCurrentNode() || {})['typename']
       },
       // 上传之前
       beforeUploadHandle (file) {
         if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
           this.$message.error('只支持jpg、png、gif格式的图片！')
           return false
         }
         this.num++
       },
       // 上传成功
       successHandle (response, file, fileList) {
         this.successNum++
         if (response && response.code === 0) {
           if (this.num === this.successNum) {
             this.fileList = fileList
           }
         } else {
           this.$message.error(response.msg)
         }
       },
       handleRemove (file, fileList) {
         this.filename = ''
         if (file.response !== undefined) {
           this.filename = file.response.name
         } else {
           this.filename = file.name
         }
         this.$http({
           url: this.$http.adornUrl(`/good/good/picdelete`),
           method: 'post',
           data: this.$http.adornData({
             name: this.filename
           })
         })
         this.fileList = fileList
       },
       limit () {
         this.$message.error('超出文件上传个数')
       },
       // 弹窗关闭时
       closeHandle () {
         this.fileList = []
         this.$emit('refreshDataList')
         this.visible = false
       },
       // 提交表单
       dataFormSubmit () {
         this.subable = true
         this.dataForm.imgurl = ''
         if (this.fileList !== undefined) {
           for (var i = 0; i < this.fileList.length; i++) {
             if (this.fileList[i].response !== undefined) {
               this.fileList[i].name = this.fileList[i].response.name
             }
             this.dataForm.imgurl += this.fileList[i].name + ','
           }
           if (this.dataForm.imgurl !== '') {
             this.dataForm.imgurl = this.dataForm.imgurl.substr(0, this.dataForm.imgurl.length - 1)
           }
         }
         this.$refs['dataForm'].validate((valid) => {
           if (valid) {
             this.$http({
               url: this.$http.adornUrl(`/good/good/${!this.dataForm.id ? 'save' : 'update'}`),
               method: 'post',
               data: this.$http.adornData({
                 'id': this.dataForm.id || undefined,
                 'typename': this.dataForm.typename,
                 'typeid': this.dataForm.typeid,
                 'name': this.dataForm.name,
                 'price': this.dataForm.price,
                 'describe': this.dataForm.describe,
                 'tag': this.dataForm.tag,
                 'remark': this.dataForm.remark,
                 'isshow': this.dataForm.isshow,
                 'sort': this.dataForm.sort,
                 'imgurl': this.dataForm.imgurl
               })
             }).then(({data}) => {
               if (data && data.code === 0) {
                 this.$message({
                   message: '操作成功',
                   type: 'success',
                   duration: 1000,
                   onClose: () => {
                     this.visible = false
                     this.fileList = []
                     this.$emit('refreshDataList')
                   }
                 })
               } else {
                 this.$message.error(data.msg)
               }
             })
           } else {
             this.subable = false
           }
         })
       }
     }
}
</script>
